﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Joz.Web.MvcExtension
{
    public static class UrlExtension
    {
        public static string ActionSearch(this UrlHelper url, RouteValueDictionary routeValues)
        {
            RouteValueDictionary route = new RouteValueDictionary(url.RequestContext.RouteData.Values);
            HttpRequestBase request = url.RequestContext.HttpContext.Request;
            foreach (var key in request.Form.AllKeys)
            {
                if (route.ContainsKey(key)) continue;
                route.Add(key, request.Form[key]);
            }
            foreach (var key in request.QueryString.AllKeys)
            {
                if (route.ContainsKey(key)) continue;
                route.Add(key, request.QueryString[key]);
            }
            foreach (var item in routeValues)
            {
                if (route.ContainsKey(item.Key)) route[item.Key] = item.Value;
                else route.Add(item.Key, item.Value);
            }
            return url.Action(url.RequestContext.RouteData.Values["action"].ToString(), url.RequestContext.RouteData.Values["controller"].ToString(), route);
        }

        public static string ActionSearch(this UrlHelper url, object routeValues)
        {
            RouteValueDictionary routeDic = new RouteValueDictionary();
            Type t = routeValues.GetType();

            PropertyInfo[] ps = t.GetProperties();
            foreach (PropertyInfo p in ps)
            {
                routeDic.Add(p.Name, p.GetValue(routeValues, null));
            }
            return ActionSearch(url, routeDic);
        }
        
    }
}
